package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.AccessType;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 按照查询条件进行数据查询
     *
     * @param searchMap 封装的查询关键字和查询条件
     * @return
     */
    @Override
    public Map search(Map<String, String> searchMap) {
        Map<String, Object> resultMap = new HashMap<>();
        //1.构建查询
        if (searchMap != null) {
            //2.构建条件查询对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

            //2.1把请求条件放入nativeSearchQueryBuilder
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //2.2如果传回关键字,封装关键字查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
                MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND);
                boolQueryBuilder.must(matchQueryBuilder);
            }
            //2.3按照品牌进行过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                //term 查询
                QueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", searchMap.get("brand"));
                boolQueryBuilder.filter(termQueryBuilder);
            }
            //2.5按照规格进行过滤查询
            //http://localhost:9009/search?keywords=手机&spec_颜色=蓝色
            for (String key : searchMap.keySet()) {
                if (key.startsWith("spec_")) {
                    String value = searchMap.get(key);
//                    value = value.replace("%2B", "+");
                    boolQueryBuilder.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", value));
                }
            }
            //2.7价格区间过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))) {
                String[] prices = searchMap.get("price").split("-");
                RangeQueryBuilder rangeQueryBuilder;
                //price=500-1000
                if (prices.length == 2) {
                    rangeQueryBuilder = QueryBuilders.rangeQuery("price").gte(prices[0]).lte(prices[1]);
                } else {
                    //price=3000
                    rangeQueryBuilder = QueryBuilders.rangeQuery("price").gte(prices[0]);
                }
                boolQueryBuilder.filter(rangeQueryBuilder);
            }

            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            //2.4按照品牌进行分组(聚合)查询
            String skuBrand = "skubrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName").size(20));

            //2.6按照规格进行分组(聚合)查询
            String skuSpec = " skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword").size(30));

            //2.8分页查询
            String pageNum = searchMap.get("pageNum");//当前页
            String pageSize = searchMap.get("pageSize");//每页显示条数
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "20";
            }
            /**
             * 注意是从第0页查询的
             */
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));

            //2.9按照相关字段进行排序查询
            //1.当前域 2.当前的排序操作(升序ASC,降序DESC)
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))) {
                if ("ASC".equals(searchMap.get("sortRule"))) {
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                } else {
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }

            //3.0设置高亮域
            //高亮字段
            HighlightBuilder.Field field = new HighlightBuilder.Field("name");
            //设置前缀
            field.preTags("<span style='color:red'>");
            //设置后缀
            field.postTags("</span>");

            nativeSearchQueryBuilder.withHighlightFields(field);

            //1.1开启查询
            /**
             * SearchQuery query    查询条件:第一个参数:条件构建对象
             * Class<T> clazz   skuInfo 查询结果封装类:第二个参数:查询实体类
             * SearchResultMapper mapper    查询结果对象;第三个参数:查询结果对象
             */
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                /**
                 *
                 * @param searchResponse    查询结果
                 * @param aClass
                 * @param pageable  分页对象
                 * @param <T>
                 * @return
                 */
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List<T> list = new ArrayList<>();
                    for (SearchHit hit : hits) {
                        //{name:zhangsan,age:12} JsonString
                        //元字符串
                        String sourceAsString = hit.getSourceAsString();
                        //转成skuInfo实体类对象
                        SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);

                        //获取高亮字段
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        if (highlightFields != null && highlightFields.size() > 0) {
                            //替换数据
                            /*
                            HighlightField highlightField = highlightFields.get("name");
                            Text[] fragments = highlightField.getFragments();
                            StringBuffer sb = new StringBuffer();
                            for (Text fragment : fragments) {
                                sb.append(fragment);
                            }
                            String hilight = sb.toString();
                            skuInfo.setName(hilight);
                            */
                            //简化写法
                            skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                        }

                        list.add((T) skuInfo);
                    }
                    //封装返回值
                    return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //根据和前端讨论的结果
            //封装最终返回结果
            //返回中记录数
            resultMap.put("total", resultInfo.getTotalElements());
            //返回总页数
            resultMap.put("totalPages", resultInfo.getTotalPages());
            //返回数据集合
            resultMap.put("rows", resultInfo.getContent());

            //封装品牌的分组结果
            List<String> brandList = new ArrayList<>();
            //获取所有的聚合
            Aggregations aggregations = resultInfo.getAggregations();
            Map<String, Aggregation> asMap = aggregations.getAsMap();
            //获取品牌的聚合
            Terms terms = (Terms) asMap.get(skuBrand);
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                String keyAsString = bucket.getKeyAsString();
                brandList.add(keyAsString);
            }
            /**简化写法
             //封装品牌的分组结果
             StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
             List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
             */
            resultMap.put("brandList", brandList);

            //封装规格的分组结果
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", formartSpec(specList));

            //当前页
            resultMap.put("pageNum", pageNum);
            return resultMap;
        }
        return null;
    }
    /**原数据格式:
     *  [
     *         "{'颜色': '蓝色', '版本': '6GB+128GB'}",
     *         "{'颜色': '黑色', '版本': '6GB+128GB'}",
     *         "{'颜色': '黑色', '版本': '4GB+64GB'}",
     *         "{'颜色': '蓝色', '版本': '4GB+64GB'}",
     *         "{'颜色': '蓝色', '版本': '6GB+64GB'}",
     *         "{'颜色': '黑色', '版本': '6GB+64GB'}",
     *         "{'颜色': '黑色'}",
     *         "{'颜色': '蓝色'}",
     *         "{'颜色': '金色', '版本': '4GB+64GB'}",
     *         "{'颜色': '粉色', '版本': '6GB+128GB'}"
     *     ]
     * 需要的数据格式:
     *      {
     *          颜色:[黑色,金色,粉色],
     *          版本:[6GB+128GB,4GB+64GB]
     *      }
     */

    /**
     * 对规格数据进行格式化
     *
     * @param stringList
     * @return
     */
    public Map<String, Set<String>> formartSpec(List<String> specList) {
        Map<String, Set<String>> resultMap = new HashMap<>();
        if (specList != null && specList.size() > 0) {
            for (String specJsonString : specList) {
                //将Json数据转换为map
                Map<String, String> specMap = JSON.parseObject(specJsonString, Map.class);
                //遍历每个商品的规格名字
                for (String specKey : specMap.keySet()) {
                    //看返回的resultMap中有此规格没有
                    Set<String> specSet = resultMap.get(specKey);
                    //如果specSet是空
                    if (specSet == null) {
                        specSet = new HashSet<>();
                    }
                    //如果不为空,将此条数据中的规格放入set
                    specSet.add(specMap.get(specKey));
                    //将set放入返回的resultMap
                    resultMap.put(specKey, specSet);
                }
            }
        }
        return resultMap;
    }
}
